package com.dandan.mobilelover.common;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StringUtil {
	private static final Logger LOG = LoggerFactory.getLogger(StringUtil.class);

	public static String getMD5Str(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(str.getBytes("UTF-8"));
		} catch (Exception e) {
			LOG.error("", e);
		} 

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString();
	}
	
	public static boolean hasLength(String str) {
		return str!=null&&!str.isEmpty();
	}
	
	public static String subString(String str,char ch,int startNumber,int endNumber) {
		char[] chares = str.toCharArray();
		List<Integer> charIndexes = new ArrayList<Integer>();
		for(int i=0;i<chares.length;++i) {
			if(chares[i]==ch) {
				charIndexes.add(i);
			}
		}
		if(startNumber>0) {
			startNumber -=1;
		}else {
			startNumber = charIndexes.size()+startNumber;
		}
		if(endNumber>0) {
			endNumber -=1;
		}else {
			endNumber = charIndexes.size()+endNumber;
		}
		if(startNumber>=endNumber
				||(startNumber<0||startNumber>=charIndexes.size())
				||(endNumber<0||endNumber>=charIndexes.size())) {
			return null;
		}
		char[] resutChars = Arrays.copyOfRange(chares, charIndexes.get(startNumber)+1, charIndexes.get(endNumber));
		return String.valueOf(resutChars);
	}
	
	public static String join(List<?> list,String separate) {
		if(list==null||list.isEmpty()) {
			return null;
		}
		StringBuffer buffer = new StringBuffer(list.get(0).toString());
		for(int i=1;i<list.size();++i) {
			Object obj = list.get(i);
			buffer.append(separate).append(obj.toString());
		}
		return buffer.toString();
	}
	
	public static void main(String[] args) {
		System.out.println(subString("http://192.168.38.18/uploads/photos/1358387867854/small/1358387867854.jpg",'/',-5,-2));
	}
}
